package com.example.xlzx.utils;



import com.example.xlzx.exception.xlzxException;
import com.example.xlzx.result.ResultCodeEnum;
import io.jsonwebtoken.*;
import io.jsonwebtoken.security.Keys;

import javax.crypto.SecretKey;
import java.util.Date;

public class JwtUtil {
    private static long tokenExpiration = 60 * 60 * 1000L * 24 * 7; // 7天
    private static SecretKey secretKey = Keys.hmacShaKeyFor("M0PKKI6pYGVWWfDZw90a0lTpGYX1d4AQ".getBytes());

    public static String createToken(Long parentId, String parentPhone) {
        String token = Jwts.builder().
                setSubject("PARENT_INFO").
                setExpiration(new Date(System.currentTimeMillis() + tokenExpiration)).
                claim("parentId", parentId).
                claim("parentPhone", parentPhone).
                signWith(secretKey).
                compact();
        return token;
    }
    public static Claims parseToken(String token){
        if (token==null){
            throw new xlzxException(ResultCodeEnum.XLZX_LOGIN_AUTH);
        }

        try{
            JwtParser jwtParser = Jwts.parserBuilder().setSigningKey(secretKey).build();
            Jws<Claims> claimsJws = jwtParser.parseClaimsJws(token);
            Claims claims= (Claims) claimsJws.getBody();
            return claims ;
        }catch (ExpiredJwtException e){
            throw new xlzxException(ResultCodeEnum.TOKEN_EXPIRED);
        }catch (JwtException e){
            throw new xlzxException(ResultCodeEnum.TOKEN_INVALID);
        }

    }


}
